package sf.database.template.freemarker.ext;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import sf.tools.StringUtils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * where指令
 */
public class WhereDirective implements TemplateDirectiveModel {
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        StringWriter writer = new StringWriter(64);
        body.render(writer);
        String content = writer.toString();
        if (StringUtils.isNotBlank(content)) {
//            content = SqlHelp.compressSql(content);
            content = content.trim();
            if (StringUtils.startsWithIgnoreCase(content, "and")) {
                content = content.substring(content.indexOf("and") + 3);
            } else if (StringUtils.startsWithIgnoreCase(content, "or")) {
                content = content.substring(content.indexOf("or") + 2);
            }
            content = " where " + content;
        }
        env.getOut().write(content);
    }

}
